package io.github.iogogogo.commons.util;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.Set;

/**
 * @author tao.zeng9@outlook.com
 * @since 2025/7/2 16:08
 */
public class ValidationUtils {
    private static final String SPLIT = "、";
    private static final Validator VALIDATOR;

    static {
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            VALIDATOR = factory.getValidator();
        }
    }


    public static void jsr303Check(Object obj) {
        if (Objects.isNull(obj)) {
            throw new IllegalArgumentException("Parameter obj could not be null!");
        } else {
            Set<ConstraintViolation<Object>> validResult = VALIDATOR.validate(obj);
            if (Objects.nonNull(validResult) && !validResult.isEmpty()) {
                StringBuilder sb = new StringBuilder(256);

                for (ConstraintViolation<Object> violation : validResult) {
                    if (StringUtils.isNotBlank(violation.getMessage())) {
                        sb.append(violation.getMessage()).append(SPLIT);
                    } else {
                        sb.append(violation.getPropertyPath().toString()).append("illegal").append(SPLIT);
                    }
                }
                throw new IllegalArgumentException(StringUtils.stripEnd(sb.toString(), SPLIT));
            }
        }
    }
}
